// 消费记录API服务
import { get, post } from './request.js';

// API基础路径 - 尝试多个可能的路径以匹配后端实际接口
const API_BASE = '/mobile';

// 获取所有消费记录（用于测试）
export const getAllConsumptionRecords = async () => {
	try {
		// 尝试多个可能的API路径
		let response;
		
		// 首先尝试主要API路径
		try {
			response = await get(`${API_BASE}/consumption-records/all`);
			console.log('主要API路径响应:', response);
		} catch (error) {
			console.log('主要API路径失败，尝试备用路径');
			// 备用路径1：直接获取消费记录
			try {
				response = await get(`${API_BASE}/consumption-records`);
				console.log('备用API路径1响应:', response);
			} catch (error2) {
				console.log('备用API路径1失败，尝试备用路径2');
				// 备用路径2：使用订单记录
				try {
					response = await get(`${API_BASE}/orders/consumption`);
					console.log('备用API路径2响应:', response);
				} catch (error3) {
					console.log('备用API路径2失败，尝试备用路径3');
					// 备用路径3：尝试其他可能的路径
					try {
						response = await get(`${API_BASE}/user/consumption`);
						console.log('备用API路径3响应:', response);
					} catch (error4) {
						console.log('所有API路径都失败，返回空数据');
						// 返回模拟数据结构，避免页面崩溃
						return {
							code: 200,
							msg: "暂无数据",
							data: []
						};
					}
				}
			}
		}
		
		console.log('所有消费记录API响应:', response);
		
		// 根据你的request.js，这里直接返回后端AjaxResult对象
		// 后端返回格式：{code: 200, msg: "操作成功", data: [...]}
		return response;
	} catch (error) {
		console.error('获取所有消费记录失败:', error);
		// 返回模拟数据结构，避免页面崩溃
		return {
			code: 200,
			msg: "获取失败，使用模拟数据",
			data: []
		};
	}
};

// 获取用户消费记录
export const getConsumptionRecords = async (userId, params = {}) => {
	try {
		const queryParams = new URLSearchParams({
			userId: userId,
			...params
		});
		
		let response;
		
		// 尝试多个可能的API路径
		try {
			response = await get(`${API_BASE}/consumption-records?${queryParams}`);
		} catch (error) {
			console.log('主要API路径失败，尝试备用路径');
			try {
				response = await get(`${API_BASE}/orders?${queryParams}`);
			} catch (error2) {
				console.log('备用API路径也失败，返回空数据');
				return {
					success: true,
					data: [],
					message: '暂无消费记录'
				};
			}
		}
		
		console.log('消费记录API响应:', response);
		
		// 检查响应结构 - 后端返回的是 AjaxResult {code: 200, msg: '操作成功', data: [...]}
		const responseData = response.data;
		
		if (responseData && responseData.code === 200) {
			const recordsArray = responseData.data;
			
			if (recordsArray && Array.isArray(recordsArray)) {
				// 转换后端数据格式为前端期望的格式
				const convertedData = recordsArray.map(record => ({
					id: record.recordId || record.id,
					title: extractServiceTitle(record.remark || record.description),
					description: record.remark || record.description || '暂无描述',
					amount: Math.abs(record.amount || 0).toFixed(2), // 取绝对值并保留两位小数
					time: record.recordTime || record.record_time || record.createTime || new Date().toLocaleString(),
					serviceType: mapServiceType(record.remark || record.description),
					status: mapStatus(record.recordType || record.record_type, record.amount || 0),
					orderNo: record.orderNumber || record.order_number || 'N/A',
					merchantName: extractMerchantName(record.remark || record.description),
					originalAmount: record.amount || 0,
					// 修复退款识别逻辑：根据金额正负判断，而不是record_type
					isRefund: (record.amount || 0) < 0
				}));
				
				console.log('转换后的消费记录数据:', convertedData);
				
				return {
					success: true,
					data: convertedData,
					message: '获取成功'
				};
			}
		}
		
		console.log('响应数据为空或格式不正确:', responseData);
		
		return {
			success: true,
			data: [],
			message: '暂无消费记录'
		};
	} catch (error) {
		console.error('获取消费记录失败:', error);
		return {
			success: false,
			data: [],
			message: '获取失败：' + (error.message || '网络错误')
		};
	}
};

// 根据类型获取消费记录
export const getConsumptionRecordsByType = async (userId, consumptionType) => {
	try {
		// 尝试多个可能的API路径
		let response;
		
		try {
			response = await get(`${API_BASE}/consumption-records/type?userId=${userId}&consumptionType=${consumptionType}`);
		} catch (error) {
			console.log('主要按类型获取消费记录API路径失败，尝试备用路径');
			try {
				response = await get(`${API_BASE}/consumption-records?userId=${userId}&type=${consumptionType}`);
			} catch (error2) {
				console.log('备用按类型获取消费记录API路径也失败，尝试备用路径2');
				try {
					response = await get(`${API_BASE}/orders?userId=${userId}&type=${consumptionType}`);
				} catch (error3) {
					console.log('备用按类型获取消费记录API路径2也失败，尝试备用路径3');
					try {
						response = await get(`${API_BASE}/user/consumption?userId=${userId}&type=${consumptionType}`);
					} catch (error4) {
						console.log('备用按类型获取消费记录API路径3也失败，尝试备用路径4');
						try {
							response = await get(`${API_BASE}/user/orders?userId=${userId}&type=${consumptionType}`);
						} catch (error5) {
							console.log('所有按类型获取消费记录API路径都失败，返回空数据');
							// 返回空数据，避免页面崩溃
							return {
								success: true,
								data: [],
								message: '暂无该类型消费记录'
							};
						}
					}
				}
			}
		}
		
		// 检查响应结构 - 后端返回的是 AjaxResult {code: 200, msg: '操作成功', data: [...]}
		const responseData = response.data;
		
		if (responseData && responseData.code === 200) {
			const recordsArray = responseData.data;
			
			if (recordsArray && Array.isArray(recordsArray)) {
				const convertedData = recordsArray.map(record => ({
					id: record.recordId || record.id,
					title: extractServiceTitle(record.remark || record.description),
					description: record.remark || record.description || '暂无描述',
					amount: Math.abs(record.amount || 0).toFixed(2),
					time: record.recordTime || record.record_time || record.createTime || new Date().toLocaleString(),
					serviceType: mapServiceType(record.remark || record.description),
					status: mapStatus(record.recordType || record.record_type, record.amount || 0),
					orderNo: record.orderNumber || record.order_number || 'N/A',
					merchantName: extractMerchantName(record.remark || record.description),
					originalAmount: record.amount || 0,
					// 修复退款识别逻辑：根据金额正负判断，而不是record_type
					isRefund: (record.amount || 0) < 0
				}));
				
				return {
					success: true,
					data: convertedData,
					message: '获取成功'
				};
			}
		}
		
		return {
			success: true,
			data: [],
			message: '暂无该类型消费记录'
		};
	} catch (error) {
		console.error('根据类型获取消费记录失败:', error);
		return {
			success: false,
			data: [],
			message: '获取失败：' + (error.message || '网络错误')
		};
	}
};

// 获取消费统计
export const getConsumptionStatistics = async (userId) => {
	try {
		// 尝试多个可能的API路径
		let response;
		
		try {
			response = await get(`${API_BASE}/consumption-records/statistics?userId=${userId}`);
		} catch (error) {
			console.log('主要统计API路径失败，尝试备用路径');
			try {
				response = await get(`${API_BASE}/orders/statistics?userId=${userId}`);
			} catch (error2) {
				console.log('备用统计API路径也失败，尝试备用路径2');
				try {
					response = await get(`${API_BASE}/user/statistics?userId=${userId}`);
				} catch (error3) {
					console.log('备用统计API路径2也失败，尝试备用路径3');
					try {
						response = await get(`${API_BASE}/statistics?userId=${userId}`);
					} catch (error4) {
						console.log('所有统计API路径都失败，返回模拟数据');
						// 返回模拟数据结构，避免页面崩溃
						return {
							code: 200,
							msg: "暂无统计数据",
							data: {
								monthlyTotal: 0,
								totalAmount: 0,
								monthlyCount: 0,
								totalCount: 0
							}
						};
					}
				}
			}
		}
		
		console.log('消费统计API响应:', response);
		
		// 根据你的request.js，这里直接返回后端AjaxResult对象
		// 后端返回格式：{code: 200, msg: "操作成功", data: {...}}
		return response;
	} catch (error) {
		console.error('获取消费统计失败:', error);
		// 返回模拟数据结构，避免页面崩溃
		return {
			code: 200,
			msg: "获取失败，使用模拟数据",
			data: {
				monthlyTotal: 0,
				totalAmount: 0,
				monthlyCount: 0,
				totalCount: 0
			}
		};
	}
};

// 模拟数据（当后端API不可用时使用）
export const getMockConsumptionRecords = async (userId, params = {}) => {
	// 模拟API调用延迟
	await new Promise(resolve => setTimeout(resolve, 500));
	
	const mockData = [
		{
			id: 1,
			title: '专业洗车服务',
			description: '郑州高新区阳光洗车店',
			amount: 35.00,
			time: '2024-01-15 14:30:00',
			serviceType: 'carwash',
			status: 'completed',
			merchantName: '阳光洗车店',
			location: '郑州高新区'
		},
		{
			id: 2,
			title: '汽车保养',
			description: '郑州高新区汽车维修中心',
			amount: 280.00,
			time: '2024-01-12 10:15:00',
			serviceType: 'maintenance',
			status: 'completed',
			merchantName: '汽车维修中心',
			location: '郑州高新区'
		},
		{
			id: 3,
			title: '应急救援',
			description: '拖车服务',
			amount: 150.00,
			time: '2024-01-10 16:45:00',
			serviceType: 'rescue',
			status: 'completed',
			merchantName: '道路救援中心',
			location: '郑州高新区'
		},
		{
			id: 4,
			title: '就近加油',
			description: '中国石油郑州高新区加油站',
			amount: 200.00,
			time: '2024-01-08 09:20:00',
			serviceType: 'fuel',
			status: 'completed',
			merchantName: '中国石油',
			location: '郑州高新区'
		}
	];
	
	// 根据服务类型筛选
	let filteredData = [...mockData];
	if (params.serviceType && params.serviceType !== 'all') {
		filteredData = filteredData.filter(record => record.serviceType === params.serviceType);
	}
	
	// 根据时间范围筛选
	if (params.startDate && params.endDate) {
		filteredData = filteredData.filter(record => {
			const recordDate = new Date(record.time);
			const startDate = new Date(params.startDate);
			const endDate = new Date(params.endDate);
			return recordDate >= startDate && recordDate <= endDate;
		});
	}
	
	return {
		success: true,
		data: filteredData,
		total: filteredData.length,
		message: '获取模拟数据成功'
	};
};

// 获取模拟消费统计
export const getMockConsumptionStatistics = async (userId) => {
	await new Promise(resolve => setTimeout(resolve, 300));
	
	return {
		success: true,
		data: {
			monthlyTotal: 665.00,
			totalAmount: 665.00,
			monthlyCount: 4,
			totalCount: 4,
			serviceTypeStats: {
				carwash: { count: 1, amount: 35.00 },
				maintenance: { count: 1, amount: 280.00 },
				rescue: { count: 1, amount: 150.00 },
				fuel: { count: 1, amount: 200.00 }
			}
		},
		message: '获取模拟统计成功'
	};
};

// 辅助函数：提取服务标题
const extractServiceTitle = (remark) => {
	if (!remark) return '消费记录';
	
	// 从备注中提取服务类型
	if (remark.includes('洗车')) return '专业洗车服务';
	if (remark.includes('打蜡')) return '汽车美容服务';
	if (remark.includes('换胎')) return '轮胎更换服务';
	if (remark.includes('保养')) return '汽车保养服务';
	if (remark.includes('维修')) return '汽车维修服务';
	if (remark.includes('加油')) return '就近加油服务';
	if (remark.includes('救援')) return '应急救援服务';
	if (remark.includes('退款')) return '退款服务';
	
	return '其他服务';
};

// 辅助函数：提取商户名称
const extractMerchantName = (remark) => {
	if (!remark) return '未知商家';
	
	// 从备注中提取商户名称
	if (remark.includes('大美汽车维修店')) return '大美汽车维修店';
	if (remark.includes('小美汽车美容店')) return '小美汽车美容店';
	if (remark.includes('中美汽车维修店')) return '中美汽车维修店';
	if (remark.includes('中国石油')) return '中国石油加油站';
	if (remark.includes('退款')) return '系统退款';
	
	return '未知商家';
};

// 辅助函数：映射服务类型
const mapServiceType = (remark) => {
	if (!remark) return 'other';
	
	if (remark.includes('洗车')) return 'carwash';
	if (remark.includes('打蜡')) return 'carwash';
	if (remark.includes('换胎')) return 'repair';
	if (remark.includes('保养')) return 'maintenance';
	if (remark.includes('维修')) return 'repair';
	if (remark.includes('加油')) return 'fuel';
	if (remark.includes('救援')) return 'rescue';
	if (remark.includes('退款')) return 'refund';
	
	return 'other';
};

// 辅助函数：映射状态
const mapStatus = (recordType, amount) => {
	// 根据金额正负判断状态，而不是record_type
	if (amount < 0) {
		return 'refunded';  // 负数表示退款
	} else {
		return 'completed'; // 正数表示消费完成
	}
};

// 将辅助函数绑定到模块
export { extractServiceTitle, extractMerchantName, mapServiceType, mapStatus };
